package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Locale;

import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnLongClick;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	private WebServicesUtil ws;
	private WSHandler handler;
	private ScanHandler shandler;
	@ViewInject(R.id.username)
	private BootstrapEditText username;
	@ViewInject(R.id.password)
	private BootstrapEditText password;
	@ViewInject(R.id.remenber)
	private CheckBox remenber;
	@ViewInject(R.id.version)
	private TextView version;
	@ViewInject(R.id.lgnum)
	private Spinner lgnum;
	private static final String[] LGNUMS={"DSZ1","AUM1"};  
	private DbUtils db;
	protected MediaPlayer mediaPlayer = null;
	protected ProgressDialog progressDialog;
	private ReadCodeController rcc;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ViewUtils.inject(this);
		// 
		shandler=new ScanHandler(this);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(shandler);
		rcc.Open();
		handler=new WSHandler(this);
		ws=new WebServicesUtil(this,handler);
		db=DbUtils.create(this,Environment.getExternalStorageDirectory().getPath() + "/storage/","storage.db");
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,LGNUMS);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lgnum.setAdapter(adapter);
		try {
			User user=db.findFirst(User.class);
			if(user!=null){
				username.setText(user.getLoginname());
				SharedPreferences sp=getSharedPreferences("PASSWORD", MODE_PRIVATE);
				String pw=sp.getString("PASSWORD", "");
				password.setText(pw);
				if(!StringUtil.isEmpty(pw)){
					remenber.setChecked(true);
				}
			}
		} catch (DbException e1) {
			e1.printStackTrace();
		}
		
		PackageManager manager = this.getPackageManager();
		try {
		        PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
		        String appVersion = info.versionName; // 版本名
//		        int appCode = info.versionCode; // 版本号
		        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
		        String szImei = TelephonyMgr.getDeviceId();
		        version.setText(" 版本:"+appVersion+"\n 设备:"+android.os.Build.MANUFACTURER+"\n IMEI:"+szImei);
		} catch (NameNotFoundException e) {
		        e.printStackTrace();
		}
		
	}
	@OnLongClick(R.id.version)
	public void goSetting(View v){
		Intent in=new Intent();
		in.setClass(this, SettingActivity.class);
		startActivity(in);
	}
	
	@OnClick(R.id.loginbutton)
	public void onClick(View v) {
		String uv=(username.getText()+"").toUpperCase(Locale.US).trim();
		String pv=(password.getText()+"").trim();
		HashMap<String, Object>params=new HashMap<String, Object>();
		if(StringUtil.isEmpty(uv)||StringUtil.isEmpty(pv)){
			new AlertDialog.Builder(LoginActivity.this).setPositiveButton("确定", null).setTitle("提示").setMessage("请输入工号和密码").show();
			return;
		}
		
		User user=new User();
		user.setWorklgnum(lgnum.getSelectedItem()+"");
		user.setLoginname(uv);
		user.setPassword(pv);
		TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();
        user.setImei(szImei);
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(user, type));
		SharedPreferences sp=getSharedPreferences("PASSWORD", MODE_PRIVATE);
		Editor editor=sp.edit();
		if (remenber.isChecked()) {
			editor.putString("PASSWORD", pv);
			editor.commit();
		}else{
			editor.putString("PASSWORD", "");
			editor.commit();
		}
		try {
			db.deleteAll(User.class);
			db.saveBindingId(user);
		} catch (DbException e1) {
			e1.printStackTrace();
		}
		progressDialog = ProgressDialog.show(LoginActivity.this, "登陆中", "请稍候...", true, true);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				WebServicesUtil.setConnectionTimeOut();
			}
		});
		ws.call(WebServicesUtil.ACTION_LOGIN, params, WebServicesUtil.URL_ACTION_LOGIN, WebServicesUtil.METHOD_ACTION_LOGIN);
	}
	//
	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// // Inflate the menu; this adds items to the action bar if it is present.
	// getMenuInflater().inflate(R.menu.main, menu);
	// return true;
	// }
	//
	//
	@OnClick(R.id.remenber)
	public void a(View v){
		return;
	}
	
	private static class WSHandler extends Handler {
		WeakReference<LoginActivity> wactivity;
		WSHandler(LoginActivity activity) {
			wactivity = new WeakReference<LoginActivity>(activity);
		}

		public void handleMessage(Message msg) {
			LoginActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_LOGIN: {
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, "帐号密码错误。\ndetail:"+msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				String loginMsg=msg.obj+"";
				try {
					Gson gson=new Gson();
					User u=gson.fromJson(loginMsg, User.class);
					User user = activity.db.findFirst(User.class);
					user.setWorklgnum(u.getWorklgnum());
					user.setUsername(u.getUsername());
					user.setLoginname(u.getLoginname());
					TelephonyManager TelephonyMgr = (TelephonyManager)activity.getSystemService(TELEPHONY_SERVICE);
			        String szImei = TelephonyMgr.getDeviceId();
					user.setImei(szImei);
					activity.db.update(user, "username","loginname","imei");
				} catch (DbException e) {
					e.printStackTrace();
				}
				Intent in=new Intent();
				in.setClass(activity,HomeActivity.class);
				if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
					activity.progressDialog.dismiss();
				}
				activity.startActivity(in);
				activity.finish();
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			activity.progressDialog.dismiss();
		}
	};
	
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static class ScanHandler extends Handler {
		WeakReference<LoginActivity> wactivity;

		ScanHandler(LoginActivity activity) {
			wactivity = new WeakReference<LoginActivity>(activity);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ReadCodeController.CODEREAD: {
				LoginActivity activity = wactivity.get();
				String old = msg.obj + "";
				View v=activity.getCurrentFocus();
				if (v instanceof EditText){
					EditText et=(EditText)v;
					et.setText(old);
				}
				activity.play_sound(true);
				break;
			}
			default:
				break;
			}
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			rcc.scan_start();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			rcc.scan_stop();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
